package com.hancher.gamelife2.videocapture;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;

import com.hancher.common.androidutil.AsyncUtils;
import com.hancher.common.androidutil.GlideEngine;
import com.hancher.common.androidutil.ImageUtil;
import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.androidutil.MmkvUtil;
import com.hancher.common.androidutil.PathUtil;
import com.hancher.common.androidutil.ToastUtil;
import com.hancher.common.base.BaseApplication;
import com.hancher.common.base.BaseFragment;
import com.hancher.common.javautil.EmptyUtil;
import com.hancher.gamelife2.databinding.FragmentCapturePictureInVideoBinding;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.functions.Consumer;

/**
 * 描述 : 扫码功能 <br/>
 * 时间 : 2024/4/16 17:27 <br/>
 * 作者 : Hancher ytu_shaoweijie@163.com
 */
public class VideoCaptureFragment extends BaseFragment<FragmentCapturePictureInVideoBinding> {
    private final static String CAPTURE_PICTURE_IN_VIDEO = "CAPTURE_PICTURE_IN_VIDEO";

    @Override
    protected void initView(Bundle savedInstanceState) {
    }

    @Override
    protected void initData() {
        String video = MmkvUtil.getString(CAPTURE_PICTURE_IN_VIDEO, "");
        binding.txtSelectVideo.setText("1. 请选择视频：\n" + video);
    }

    @Override
    protected void initListener() {
        binding.btnSelectVideo.setOnClickListener(v -> {
            PictureSelector.create(getContext())
                    .openGallery(SelectMimeType.ofVideo())
                    .setImageEngine(GlideEngine.createGlideEngine())

                    .setMaxSelectNum(1)
                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {
                            for (LocalMedia item : result) {
                                LogUtil.o(item);
                            }
                            if (EmptyUtil.isEmpty(result)) {
                                ToastUtil.showErr("选择文件失败!");
                                return;
                            }
                            MmkvUtil.put(CAPTURE_PICTURE_IN_VIDEO, result.get(0).getRealPath());
                            binding.txtSelectVideo.setText("1. 请选择视频：\n" + result.get(0).getRealPath());
                        }

                        @Override
                        public void onCancel() {

                        }
                    });
        });


        // 2 视频截取图片
        binding.btnFastSelectPicture.setOnClickListener(v -> {
            deleteOldFile();
        });

        binding.tvDelete.setOnClickListener(v -> {
            AsyncUtils.run(emitter -> {
                File dir = new File(PathUtil.OUT_PUBLIC_DOWNLOAD, "VideoCapture");
                File[] files = dir.listFiles();
                if (files == null || files.length == 0) {
                    emitter.onNext(false);
                    emitter.onComplete();
                    return;
                }
                for (File item : files) {
                    if (item.exists()) {
                        item.delete();
                    }
                }
                Uri uri = Uri.fromFile(dir);
                BaseApplication.getInstance().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                emitter.onNext(true);
                emitter.onComplete();
            }, (Consumer<Boolean>) aBoolean -> {
                ToastUtil.show("清理完成");
            }, ToastUtil::showErr);
        });
    }

    private void deleteOldFile() {
        AsyncUtils.run(emitter -> {
            File dir = new File(PathUtil.OUT_PUBLIC_DOWNLOAD, "VideoCapture");
            File[] files = dir.listFiles();
            if (files == null || files.length == 0) {
                emitter.onNext(false);
                emitter.onComplete();
                return;
            }
            for (File item : files) {
                if (item.exists()) {
                    item.delete();
                }
            }
            Uri uri = Uri.fromFile(dir);
            BaseApplication.getInstance().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            emitter.onNext(true);
            emitter.onComplete();
        }, (Consumer<Boolean>) aBoolean -> {
            startCapture();
        }, ToastUtil::showErr);
    }

    private void startCapture() {
        String videoPath = MmkvUtil.getString(CAPTURE_PICTURE_IN_VIDEO, "");
        int time;
        try {
            time = Integer.parseInt(binding.editCapture.getEditableText().toString());
        } catch (NumberFormatException e) {
            ToastUtil.showErr(e.getMessage());
            return;
        }
        WaitDialog waitDialog = WaitDialog.show("正在视频截图...", 0.0001f);
        AsyncUtils.run(emitter -> {
            File dir = new File(PathUtil.OUT_PUBLIC_DOWNLOAD, "VideoCapture");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            LogUtil.d("开始视频截图 位置=%s 时间=%d 视频输出位置=%s", videoPath, time, dir.getAbsolutePath());
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(videoPath);
            int duration = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));//时长(毫秒)
            LogUtil.d("视频总时长为:%d", duration);
            int every = duration / time;
            //这里传入的时间是  微秒  值,单位需要自己换算
            List<String> data = new ArrayList<>();
            for (int i = 0; i < time; i++) {
                Bitmap bitmap = retriever.getFrameAtTime((every / 2 + every * i) * 1000, MediaMetadataRetriever.OPTION_CLOSEST);
                LogUtil.d("截取图片 时间=%d 图片=%s", (every / 2 + every * i), bitmap.toString());
                if (bitmap != null) {
                    try {
                        String file = ImageUtil.saveBitmap2File(bitmap, dir.getAbsolutePath());
                        data.add(file);
                    } catch (IOException e) {
                        LogUtil.e(e);
                        data.add("");
                    }
                }
                emitter.onNext(data);
            }
            emitter.onComplete();
        }, (Consumer<List<String>>) pictures -> {
            if (pictures.size() != time) {
                waitDialog.setProgress(1f * pictures.size() / time);
                return;
            }
            waitDialog.doDismiss();
            LogUtil.d("截图成功:" + pictures);
            binding.tvCaptureResult.setText("截取图片：\n" + pictures);
        }, ToastUtil::showErr);
    }


}